<?php
/**
 * Stores files in self::$fileDir (ex."files") using unique names on save
 * allowing only one file (substituting)
 */
class SimpleUploadWidget extends UploadWidget {
    const NAME = 'simpleUploadWidget';

    const DELETE_ACTION = 'delete';

    public $maxFiles = 3;

    /** Default view of the widget */
    public function run() {
        $model = $this->getOwner();
        if ($model!=null) {
            $files = $model->files;
            $this->render('fileList', array(
                'files'=>$files,
            ));
            
            if (count($files) < $this->maxFiles) {
                $this->render('uploadWidget', array('name' => self::NAME));
            }
        }
    }
    /** File list with delete option */
    public function runFileList() {
        $model = $this->getOwner();
        if ($model!=null) {
            $files = $model->files;
            $this->render('fileList', array(
                'files'=>$files,
            ));
        }
    }

    public static function actions() {
        return array(
            self::DELETE_ACTION => array(
                'class'=>'ext.upload.simple.actions.DeleteAction',
            ),
        );
    }



    ///////////////////////////////////////////////////////////////////// Events
    public function events() {
        return array(
                //'onBeforeSave'=>'beforeSave',
                'onAfterSave'=>'afterSave',
                //'onBeforeDelete'=>'beforeDelete',
                'onAfterDelete'=>'afterDelete',
                //'onAfterConstruct'=>'afterConstruct',
                //'onBeforeFind'=>'beforeFind',
                //'onAfterFind'=>'afterFind',
        );
    }

    public function afterSave($event) {
        if (!empty($_FILES)) {
            $model = $this->getOwner();

            $file=new File;
            $file->filename = UploadUtils::createUniquefilename(
                    $_FILES[self::NAME]['name'],
                    UploadUtils::getPath(self::$fileDir));
            if (move_uploaded_file(
                $_FILES[self::NAME]['tmp_name'],
                UploadUtils::getPath(self::$fileDir).DIRECTORY_SEPARATOR.$file->filename
            )) {
                $file->entity   = get_class($model);
                $file->EXid     = $model->getPrimaryKey();
                $file->uid      = Yii::app()->user->id;
                $file->weight   = 0;
                $file->timestamp= time();
                $file->filemime = CFileHelper::getMimeTypeByExtension($_FILES[self::NAME]['name']);
                $file->filesize = $_FILES[self::NAME]['size'];
                $file->status   = 1;

                // Ensure all other files of the entity are deleted
                //UploadUtils::deleteAllFiles(get_class($this->getOwner()), self::$fileDir);

                if ($file->save()) {
                    Yii::trace("File saved ".$file."!!!!");
                } else {
                    Yii::log("Could not save File ".print_r($file->getErrors(), true), CLogger::LEVEL_ERROR);
                }
            } else {
                Yii::log("Couldnt move the file", CLogger::LEVEL_ERROR);
            }
        } else {
            Yii::log("Files empty!!!", CLogger::LEVEL_ERROR);
        }
    }
    /** Delete all files associated to this model */
    public function afterDelete() {
        UploadUtils::deleteFiles($this->getOwner(), self::$fileDir);
    }

}